<template>
  <a-modal
    :wrapClassName="fullScreen ? 'modal-wrap-fullscreen' : ''"
    :visible="visible"
    :width="fullScreen ? '100%' : 1200"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :bodyStyle="fullScreen ? bodyStyle : {}"
  >
    <div slot="title">
      {{ title }}
      <a-icon class="icon-alt" :type="fullScreen ? 'shrink' : 'arrows-alt'" @click="toggleFullScreen" />
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="form"
        :labelCol="layout.labelCol"
        :wrapperCol="layout.wrapperCol"
        v-bind="layout"
        :model="model"
        :rules="validatorRules"
      >
        <div class="head">
          <a-row style="width: 100%">
            <a-col :span="8">
              <a-form-model-item label="表名" required prop="tableName">
                <a-input v-model="model.tableName" :disabled="roleDisabled" placeholder="请输入表名" />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="表描述" required prop="tableTxt">
                <a-input v-model="model.tableTxt" placeholder="请输入表描述" /> </a-form-model-item
            ></a-col>
            <a-col :span="8">
              <a-form-model-item label="表类型" prop="tableType">
                <a-select style="width: 100%" v-model="model.tableType" placeholder="请输入表类型">
                  <a-select-option :value="item.value" v-for="item in tableTypeDictOptions" :key="item.label">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <!-- <div style="display: flex;justify-content: space-between;">
                <a-radio-group name="radioGroup" :default-value="1" v-model="radioGroup">
                  <a-radio :value="1">一对一</a-radio>
                  <a-radio :value="2">一对多</a-radio>
                </a-radio-group>
                <a-form-model-item label="序号" required prop="tableName">
                <a-input-number v-model="model.tableName" :min="-10000" :max="10000" />
              </a-form-model-item>
              </div> -->
            </a-col>
          </a-row>
        </div>
        <div class="head" v-show="model.tableType === 2 && model.id">
          <a-row class="ftable">
            <div class="label">附表<span style="margin: 0 8px 0 2px">:</span></div>
            <a-input v-model="model.subTableStr" disabled placeholder="" />
          </a-row>
        </div>
        <!-- {{this.$refs.editableTable1.getValues()}} -->
        <div>
          <a-tabs @change="handleChangeTab" v-model="tab">
            <a-tab-pane key="1" tab="数据库属性" :forceRender="true">
              <j-editable-table
                ref="editableTable1"
                :loading="tab1loading"
                id="editableTable1"
                :columns="tab1Columns"
                :dataSource="tab1Data"
                :disabledRows="{ rowKey: disabledRows }"
                :rowNumber="true"
                :rowSelection="true"
                :dragSort="true"
                @deleted="deletedTab1"
                :actionButton="true"
                style="margin-top: 8px"
                @selectRowChange="handleSelectRowChange"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="外键" :forceRender="true">
              <!-- {{tab2Data}} -->
              <j-editable-table
                ref="editableTable2"
                :loading="tab2loading"
                :columns="tab2Columns"
                :dataSource="tab2Data"
                :rowNumber="true"
                :disabledRows="{ rowKey: disabledRows }"
                style="margin-top: 8px"
                @selectRowChange="handleSelectRowChange"
              />
            </a-tab-pane>
            <a-tab-pane key="3" tab="索引" :forceRender="true">
              <j-editable-table
                ref="editableTable3"
                :loading="tab3loading"
                :columns="tab3Columns"
                :dataSource="tab3Data"
                :rowNumber="true"
                @deleted="deletedTab3"
                :rowSelection="true"
                :actionButton="true"
                style="margin-top: 8px"
                @selectRowChange="handleSelectRowChange"
              />
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { addOnlineTables, editAllOnline, queryByTable, fieldqueryByTable, indexqueryByTable } from '@/api/api'
import { FormTypes } from '@/utils/JEditableTableUtil'
const init = [
  {
    dbFieldName: 'id',
    dbFieldTxt: '主键',
    dbLength: 36,
    dbType: 'String',
    dbIsKey: 1,
    dbIsNull: 0,
    dbPointLength: 0,
    rowKey: 1,
    orderNum: 1,
    id: '1',
  },
  {
    dbFieldName: 'create_by',
    dbFieldTxt: '创建人',
    dbLength: 50,
    dbType: 'String',
    dbIsNull: 1,
    dbPointLength: 0,
    dbIsKey: 0,
    rowKey: 2,
    orderNum: 2,
    id: '2',
  },
  {
    dbFieldName: 'create_time',
    dbFieldTxt: '创建日期',
    dbLength: 20,
    dbType: 'Date',
    dbIsNull: 1,
    dbPointLength: 0,
    dbIsKey: 0,
    rowKey: 3,
    id: '3',
    orderNum: 3,
  },
  {
    dbFieldName: 'update_by',
    dbFieldTxt: '更新人',
    dbLength: 50,
    dbType: 'String',
    dbIsNull: 1,
    dbPointLength: 0,
    dbIsKey: 0,
    rowKey: 4,
    id: '4',
    orderNum: 4,
  },
  {
    dbFieldName: 'update_time',
    dbFieldTxt: '更新日期',
    dbLength: 20,
    dbType: 'Date',
    dbPointLength: 0,
    dbIsNull: 1,
    dbIsKey: 0,
    rowKey: 5,
    id: '5',
    orderNum: 5,
  },
  {
    id: '6',
    dbFieldName: 'sys_org_code',
    dbFieldTxt: '所属部门',
    dbLength: 64,
    dbType: 'String',
    dbPointLength: 0,
    dbIsNull: 1,
    dbIsKey: 0,
    rowKey: 6,
    orderNum: 6,
  },
]
export default {
  name: 'addOnline',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      // init,
      deleteFieldIds: [],
      deleteIndexIds: [],
      tab: '1',
      disabledRows: 1,
      tab1loading: false,
      tab3Data: [],
      tab2Data: [],
      tab1Data: [],
      tab2Columns: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          disabled: true,
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '字段备注',
          key: 'dbFieldTxt',
          disabled: true,
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '主表名',
          key: 'mainTable',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
        },
        {
          title: '主表字段',
          key: 'mainField',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
        },
      ],
      tab1Columns: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          //   defaultValue: '称名',
          // 表单验证规则
          validateRules: [
            {
              required: true, // 必填
              message: '${title}不能为空', // 提示的文本
            },
            {
              pattern: /^[A-Za-z]{1}[A-Za-z0-9$]{1}[A-z0-9_$]{0,}$/, // 正则
              message: '命名规则:只能由字母、数字、下划线、$符号组成;必须以字母开头;不能以单个字母加下滑线开头',
              // /^[a-z|A-Z][a-z|A-Z\d_$]{0,}$/
            },
            // {
            //   pattern:/^[a-z|A-Z][a-z|A-Z\d_$]{0,}$/,
            //   message: '命名规则:只能由字母、数字、下划线、$符号组成;必须以字母开头;不能以单个字母加下滑线开头',
            // },
            {
              // 自定义函数校验 handler
              handler(type, value, row, column, callback, target) {
                // type 触发校验的类型（input、change、blur）
                // value 当前校验的值
                // callback(flag, message) 方法必须执行且只能执行一次
                //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                //          message = 提示的消息，默认使用配置的 message
                // target 行编辑的实例对象

                if (type === 'blur') {
                  let { values } = target.getValuesSync({ validate: false })
                  let count = 0
                  for (let val of values) {
                    if (val['dbFieldName'] === value) {
                      if (++count >= 2) {
                        callback(false, '${title}不能重复')
                        return
                      }
                    }
                  }
                  callback(true) // true = 通过验证
                } else {
                  callback() // 不填写或者填写 null 代表不进行任何操作
                }
              },
              message: '${title}默认提示',
            },
          ],
        },

        {
          title: '字段备注',
          key: 'dbFieldTxt',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '字段长度',
          key: 'dbLength',
          type: FormTypes.inputNumber,
          placeholder: '请输入${title}',
          defaultValue: '32',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '小数点',
          key: 'dbPointLength',
          type: FormTypes.inputNumber,
          placeholder: '请输入${title}',
          defaultValue: '0',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '默认值',
          key: 'dbDefaultVal',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
          // validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '字段类型',
          key: 'dbType',
          //   width:'120px',
          type: FormTypes.select,
          options: [
            {
              text: 'String',
              value: 'String',
            },
            {
              text: 'Integer',
              value: 'Integer',
            },
            {
              text: 'Double',
              value: 'Double',
            },
            {
              text: 'Date',
              value: 'Date',
            },
            {
              text: 'BigDecimal',
              value: 'BigDecimal',
            },
            {
              text: 'Text',
              value: 'Text',
            },
            {
              text: 'Blob',
              value: 'Blob',
            },
          ],
          placeholder: '请输入${title}',
          defaultValue: 'String',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '主键',
          key: 'dbIsKey',
          type: FormTypes.checkbox,
          placeholder: '请输入${title}',
          customValue: ['1', '0'],
          defaultValue: '',
          width: '80px',
          disabled: true,
          // validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '允许空值',
          width: '80px',
          key: 'dbIsNull',
          customValue: ['1', '0'],
          type: FormTypes.checkbox,
          defaultChecked: true,
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
      ],
      tableTypeDictOptions: [
        {
          label: '单表',
          value: 1,
        },
        {
          label: '主表',
          value: 2,
        },
        {
          label: '附表',
          value: 3,
        },
      ],
      fullScreen: false,
      bodyStyle: {
        height: '89vh',
      },
      // title: '操作',
      // visible: false,
      roleDisabled: false,
      model: {
        tableType: 1,
        subTableStr: '',
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
      },
      tab2loading: false,
      tab3loading: false,
      confirmLoading: false,
      indexFieldArr: [],
      validatorRules: {
        tableTxt: [
          { required: true, message: '请输入表描述!' },
          { min: 0, max: 30, message: '长度不超过 30 个字符', trigger: 'blur' },
        ],
        tableName: [
          { required: true, message: '请输入表名称!' },
          { min: 0, max: 64, message: '长度不超过 64 个字符', trigger: 'blur' },
          // { pattern:, message: '不能全部是数字', trigger: 'blur' },
          { validator: this.validateRoleCode },
        ],
        description: [{ min: 0, max: 126, message: '长度不超过 126 个字符', trigger: 'blur' }],
      },
      tab3Columns: [
        {
          title: '索引名称',
          key: 'indexName',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [
            { required: true, message: '${title}不能为空' },
            {
              pattern: /^[a-z|A-Z][a-z|A-Z\d_$]{0,}$/, // 正则
              message: '只允许字母下划线数字$且数字不能开头',
              // /^[a-z|A-Z][a-z|A-Z\d_$]{0,}$/
            },
          ],
        },
        {
          title: '索引栏位',
          key: 'indexField',
          type: FormTypes.list_multi,
          options: [],
          placeholder: '请输入${title}',
          defaultValue: '',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '索引类型',
          key: 'indexType',
          type: FormTypes.select,
          options: [
            {
              text: 'normal',
              value: 'normal',
            },
            {
              text: 'unique',
              value: 'unique',
            },
          ],
          placeholder: '请输入${title}',
          defaultValue: 'normal',
        },
      ],
    }
  },
  created() {},
  methods: {
    deletedTab1(v) {
      this.deleteFieldIds = v
    },
    deletedTab3(v) {
      this.deleteIndexIds = v
    },
    getData() {
      // if (this.$refs.editableTable1) {
      //   this.$refs.editableTable1.initialize()
      // }
      // this.tab1Data = []
      console.log(init, 'init')
      this.tab3Data = []
      this.tab1Data = init
      this.disabledRows = 1
      this.tab3Data = []
      this.resetForm()
    },
    getTabValues(v) {
      let { error, values } = this.$refs[v].getValuesSync({
        validate: false,
      })
      return values || []
    },
    handleSelectRowChange() {},
    /** 切换tab选项卡的时候重置editableTable的滚动条状态 */
    handleChangeTab(key) {
      const tab1 = this.getTabValues('editableTable1')
      const tab2 = this.getTabValues('editableTable2')
      this.tab2Data = tab1.map((i) => {
        const tab2fil = tab2.filter((d) => {
          return d.id === i.id
        })
        return {
          ...i,
          mainField: tab2fil.length > 0 ? tab2fil[0].mainField : '',
          mainTable: tab2fil.length > 0 ? tab2fil[0].mainTable : '',
          rowKey: i.id,
        }
      })
      this.tab3Columns[1].options = []
      tab1.forEach((item) => {
        if (item.dbFieldName) {
          this.tab3Columns[1].options.push({
            label: item.dbFieldName,
            value: item.dbFieldName,
          })
        }
      })
      if (this.$refs[`editableTable${key}`]) {
        this.$refs[`editableTable${key}`].resetScrollTop()
      }
    },
    toggleFullScreen() {
      this.fullScreen = !this.fullScreen
    },
    resetScroll() {
      if (this.$refs.editableTable1) {
        console.log(this.$refs.editableTable1)
        this.$nextTick(() => {
          document.querySelector('.scroll-view').scrollTop = 0
        })
      }
    },
    add() {
      this.resetScroll()
      // this.edit({})
    },
    edit(record) {
      this.tab1loading = true
      this.tab2loading = true
      this.tab3loading = true
      queryByTable({ id: record.id }).then((res) => {
        this.model = Object.assign({}, record)
      })
      fieldqueryByTable({ headId: record.id }).then((res) => {
        let data = res.result.map((d, index) => {
          return {
            ...d,
            rowKey: d.id,
          }
        })
        this.tab1Data = data || []
        this.tab2Data = data || []
        const findId = data.find((item) => item.dbFieldName === 'id')
        this.disabledRows = findId ? findId.id : ''
      })
      indexqueryByTable({ headId: record.id }).then((res) => {
        this.tab3Data = res.result || []
      })
      this.resetScroll()
      setTimeout(() => {
        this.tab1loading = false
        this.tab2loading = false
        this.tab3loading = false
        // this.confirmLoading = false
      }, 1000)
      if (this.model.id) {
        // this.roleDisabled = true
      } else {
        this.roleDisabled = false
      }
    },
    close() {
      this.$emit('close')
      this.tab = '1'
      this.resetScroll()
      this.tab1Data = []
      // if (this.$refs.editableTable1) {
      //   this.$refs.editableTable1.initialize()
      // }
      // this.visible = false;
    },
    isTableValidate(v) {
      let { error, values } = this.$refs[v].getValuesSync({ validate: true })
      let res
      if (error === 0) {
        res = values
      } else {
        res = error
      }
      return res
    },
    handleOk() {
      const that = this
      // 触发表单验证
      that.$refs.form.validate((valid) => {
        if (valid) {
          let fields = []
          let indexs = []
          const editableTable1 = that.isTableValidate('editableTable1')
          if (typeof editableTable1 === 'object') {
            let { error, values } = this.$refs.editableTable2.getValuesSync({ validate: true })
            if (error === 0) {
              fields = editableTable1.map((item) => {
                const obj = values.filter((v) => {
                  return v.id === item.id
                })
                console.log(obj, 'obj')
                return {
                  ...item,
                  mainTable: obj.length > 0 ? obj[0].mainTable : '',
                  mainField: obj.length > 0 ? obj[0].mainField : '',
                }
              })
            }
          } else {
            that.$antdMessage.warning('数据库属性列表报错')
            // this.tab = 1
            return 'BAOCUO'
          }
          const editableTable3 = that.isTableValidate('editableTable3')
          if (typeof editableTable3 === 'object') {
            indexs = editableTable3
          } else {
            that.$antdMessage.warning('索引列表报错')
            // this.tab = 3
            return 'BAOCUO'
          }
          let params = {
            deleteFieldIds: [],
            deleteIndexIds: [],
            head: this.model,
            fields: fields,
            indexs: indexs,
          }
          console.log(params, 'paramsparams')
          that.confirmLoading = true
          let obj
          if (!this.model.id) {
            obj = addOnlineTables(params)
          } else {
            params.deleteFieldIds = this.deleteFieldIds
            params.deleteIndexIds = this.deleteIndexIds
            obj = editAllOnline(params)
          }
          obj
            .then((res) => {
              if (res.success) {
                that.$antdMessage.success(res.message)
                that.close()
                that.$emit('ok')
              } else {
                that.$antdMessage.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              // that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.resetForm()
      this.close()
    },
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
        this.model = { tableType: 1, subTableStr: '' }
      }
    },
    validateRoleCode(rule, value, callback) {
      // var reg = /^[a-zA-Z0-9_]{0,}$/ || !reg.test(value) 中文和特殊字符
      // (/^[0-9]*$/g.test(value)
      if (/^[a-z|A-Z][a-z|A-Z\d_$]{0,}$/.test(value)) {
        callback()
      } else {
        callback('只允许字母下划线数字$且数字不能开头')
      }
    },
  },
}
</script>
<style lang="less" scoped>
.head {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  width: 100%;
}
.modal-wrap-fullscreen {
  height: 100vh;
  width: 100%;
  overflow: hidden;
  .ant-modal {
    top: 0px;
  }
}
.icon-alt {
  position: absolute;
  right: 60px;
  top: 19px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 16px;
}
.ftable {
  align-items: center;
  display: flex;
  width: 100%;
}
.label {
  width: 81px;
  padding-left: 35px;
  color: rgba(0, 0, 0, 0.85);
}
</style>
